<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/20/020
 * Time: 15:13
 */

namespace app\admin\controller;
use app\api\model\Product as ProductModel;
use app\api\service\Upload;
use app\api\validate\IDMustBePostiveInt;
use app\api\validate\ProductValidate;
use app\api\model\Brand as BrandModel;
use app\api\model\Category as CategoryModel;
use app\api\model\ProductImage as ProductImageModel;
use think\Exception;


class Product extends Base {

    /**
     * 产品列表
     * @return \think\response\Json|\think\response\View
     */
    public function index() {
        if (request()->isAjax()) {
            $data = ProductModel::getList()->toArray();
            return admin_return_data('产品列表', $data['total'], $data['data']);
        }
        return view();
    }

    /**
     * 创建或者编辑品牌
     * @return \think\response\Json|\think\response\View
     * @throws \app\api\exception\ParameterException
     * @throws \think\exception\DbException
     */
    public function save_product() {
        $id = input('param.id', 0);
        if (request()->isAjax()) {
            $product_validate = new ProductValidate();
            $product_validate->goCheck();
            $param = $product_validate->getDataByRule(input('param.'));
            $data = ProductModel::createOrUpdateProduct($param, $id);
            return json($data);
        } else {
            $data = [];
            if ($id > 0) {
                $data = ProductModel::get($id);
            }
            $this->assign('data', $data);

            // 获取全部品牌
            $brands = BrandModel::all();
            $this->assign('brands', $brands);

            // 获取全部分类
            $categorys = CategoryModel::getCates();;
            $this->assign('categorys', $categorys);

            return view();
        }
    }

    /**
     * 上传产品图片
     * @return \think\response\Json|\think\response\View
     * @throws \app\api\exception\ParameterException
     * @throws \think\exception\DbException
     */
    public function save_image() {
        (new IDMustBePostiveInt())->goCheck();
        $id = input('param.id');

        $type = input('param.type', '');
        if (!in_array($type, ['list', 'content'])) {
            return json(['code' => 1, 'msg' => '参数错误！']);
        }

        if (request()->isAjax()) {
            $data = Upload::upload_file();
            $product_image_data = [
                'product_id' => $id,
                'image' =>  $data['path'],
                'type' => $type == 'list' ? 1 : 2
            ];
            ProductImageModel::create($product_image_data);

            return json([
                'code' => $data['code'],
                'msg' => $data['msg'],
                'data' => [
                    'src' => $data['path']
                ]
            ]);
        } else {

            $data = productModel::get($id, [$type . '_image']);
            $this->assign('data', $data);

            $this->assign('type', $type);

            return view();
        }
    }

    /**
     * 获取图片列表
     * @return \think\response\Json
     * @throws \app\api\exception\ParameterException
     * @throws \think\exception\DbException
     */
    public function image_list() {
        (new IDMustBePostiveInt())->goCheck();
        $id = input('param.id');

        $type = input('param.type', '');
        if (!in_array($type, ['list', 'content'])) {
            return json(['code' => 1, 'msg' => '参数错误！']);
        }

        $type = $type == 'list' ? 1 : 2;

        $images = ProductImageModel::all(function($query) use ($id, $type) {
            $query->where('product_id', '=', $id)->where('type', '=', $type)->order('sort asc');
        });
        $images->toArray();
        return admin_return_data('产品图片列表', count($images), $images);
    }

    /**
     * 修改图片信息
     * @return \think\response\Json
     * @throws \app\api\exception\ParameterException
     * @throws \think\exception\DbException
     */
    public function save_image_info() {
        (new IDMustBePostiveInt())->goCheck();
        $id = input('param.id');

        $image = ProductImageModel::get($id);
        if (!$image) {
            return json(['code' => 1, 'msg' => '图片不存在']);
        }

        $field = input('param.field');
        $value = input('param.value');
        try {
            $image->save([$field => $value]);
            return json(['code' => 0, 'msg' => '修改成功！']);
        } catch (Exception $e) {
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }
}